package com.atguigu.lease.web.admin.interceptor;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    //在请求controller接口前进行拦截，校验token令牌
    //  Json web token    ->   jwt
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("ACCESS_TOKEN");//获取请求头中令牌
        if(StringUtils.isEmpty(token)){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH); // 未登录
        }
        Claims claims = JwtUtil.parseToken(token); //令牌合法直接返回true,否则自动抛出异常。
        Long userId = claims.get("userId", Long.class);
        String username = claims.get("username", String.class);
        //如何将数据往线程上绑定。这里使用TheadLocal工具类
        LoginUser loginUser = new LoginUser(userId,username);
        LoginUserContext.setLoginUser(loginUser);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContext.clear();
    }
}
